package myJs.user.predict

import myJs.Utils._
import myJs.api.Api
import myJs.cps._
import myJs.myPkg.d3v4.d3
import myJs.myPkg.jquery.{$, JQueryAnimationSettings}
import myJs.myPkg.{LayerOptions, layer}
import myJs.myPkg.reactBootstrap.Modal
import myJs.myPkg.reactHookForm._
import myJs.tool.Tool
import org.scalajs.macrotaskexecutor.MacrotaskExecutor.Implicits._
import shared.pojo.Pojo.predict._
import slinky.core.FunctionalComponent
import slinky.core.annotations.react
import slinky.core.facade.Hooks._
import slinky.web.html._
import typings.csstype.csstypeStrings

import scala.scalajs.js
import scala.scalajs.js.{Date, JSON}
import com.softwaremill.quicklens._

import scala.collection.SeqMap
import myJs.Implicits._
import shared.pojo.User.{PdfInfo, UserIdData}
import io.scalaland.chimney.dsl._

/** Created by yz on 21/1/2022
  */
@react object MyToolCp {

  case class Props(
      row: PredictResult.Response,
      show: Boolean = false,
      showChange: Boolean => Unit,
      time: String
  )

  val component = FunctionalComponent[Props] { props =>
    val useForm = ReactHookForm.useForm(UseFormOptions(mode = "onChange"))
    val (myData, setMyData) = useState(Export.Request())
    val (pdfInfo, setPdfInfo) = useState(PdfInfo())
    object FTool {
      def handleClose = () => {
        props.showChange(false)
      }

      def formSubmit = useForm.handleSubmit((data: js.Dictionary[js.Any]) => {
        println(JSON.stringify(data))
        FTool.export()
      })

      def sampleSubmitTimeCheck = {
        if (!myData.sampleTime.strIsBlank && !myData.submitTime.strIsBlank) {
          val sampleTime = new Date(myData.sampleTime)
          val submitTime = new Date(myData.submitTime)
          if (sampleTime.getTime() > submitTime.getTime()) {
            layer.msg("采样时间不能大于送检时间", LayerOptions(icon = 5, time = 3000))
            false
          } else true
        } else true
      }

      def checkReportDateCheck = {
        if (!myData.checkDate.strIsBlank && !myData.reportDate.strIsBlank) {
          val checkDate = new Date(myData.checkDate)
          val reportDate = new Date(myData.reportDate)
          if (checkDate.getTime() > reportDate.getTime()) {
            layer.msg("检验日期不能大于报告日期", LayerOptions(icon = 5, time = 3000))
            false
          } else true
        } else true
      }

      def export = () => {
        if (sampleSubmitTimeCheck && checkReportDateCheck) {
//          $("#exportForm").submit()
          println("export exec")
        }
        ()
      }

      def titleChange = (v: String) => {
        val newRow = myData.modify(_.title).setTo(v)
        setMyData(newRow)
      }
      def dangerChange = (v: String) => {
        val newRow = myData.modify(_.danger).setTo(v)
        setMyData(newRow)
      }
      def unitChange = (v: String) => {
        val newRow = myData.modify(_.unit).setTo(v)
        setMyData(newRow)
      }
      def addressChange = (v: String) => {
        val newRow = myData.modify(_.address).setTo(v)
        setMyData(newRow)
      }
      def sexChange = (v: String) => {
        val newRow = myData.modify(_.sex).setTo(v)
        setMyData(newRow)
      }
      def nameChange = (v: String) => {
        val newRow = myData.modify(_.name).setTo(v)
        setMyData(newRow)
      }
      def ageChange = (v: String) => {
        val newRow = myData.modify(_.age).setTo(v)
        setMyData(newRow)
      }
      def officeChange = (v: String) => {
        val newRow = myData.modify(_.office).setTo(v)
        setMyData(newRow)
      }
      def doctorChange = (v: String) => {
        val newRow = myData.modify(_.doctor).setTo(v)
        setMyData(newRow)
      }
      def numberChange = (v: String) => {
        val newRow = myData.modify(_.number).setTo(v)
        setMyData(newRow)
      }
      def sampleTimeChange = (v: String) => {
        val newRow = myData.modify(_.sampleTime).setTo(v)
        setMyData(newRow)
      }
      def submitTimeChange = (v: String) => {
        val newRow = myData.modify(_.submitTime).setTo(v)
        setMyData(newRow)
      }
      def sampleIdChange = (v: String) => {
        val newRow = myData.modify(_.sampleId).setTo(v)
        setMyData(newRow)
      }
      def sampleTypeChange = (v: String) => {
        val newRow = myData.modify(_.sampleType).setTo(v)
        setMyData(newRow)
      }
      def sampleStatusChange = (v: String) => {
        val newRow = myData.modify(_.sampleStatus).setTo(v)
        setMyData(newRow)
      }
      def reporterChange = (v: String) => {
        val newRow = myData.modify(_.reporter).setTo(v)
        setMyData(newRow)
      }
      def checkerChange = (v: String) => {
        val newRow = myData.modify(_.checker).setTo(v)
        setMyData(newRow)
      }
      def checkDateChange = (v: String) => {
        val newRow = myData.modify(_.checkDate).setTo(v)
        setMyData(newRow)
      }
      def reportDateChange = (v: String) => {
        val newRow = myData.modify(_.reportDate).setTo(v)
        setMyData(newRow)
      }
      def testMethodChange = (v: String) => {
        val newRow = myData.modify(_.testMethod).setTo(v)
        setMyData(newRow)
      }
      def astChange = (v: String) => {
        val newRow = myData.modify(_.ast).setTo(v)
        setMyData(newRow)
      }
      def altChange = (v: String) => {
        val newRow = myData.modify(_.alt).setTo(v)
        setMyData(newRow)
      }
      def pltChange = (v: String) => {
        val newRow = myData.modify(_.plt).setTo(v)
        setMyData(newRow)
      }
      def tcaChange = (v: String) => {
        val newRow = myData.modify(_.tca).setTo(v)
        setMyData(newRow)
      }
      def tyrChange = (v: String) => {
        val newRow = myData.modify(_.tyr).setTo(v)
        setMyData(newRow)
      }
      def pheChange = (v: String) => {
        val newRow = myData.modify(_.phe).setTo(v)
        setMyData(newRow)
      }
      def trpChange = (v: String) => {
        val newRow = myData.modify(_.trp).setTo(v)
        setMyData(newRow)
      }
      def valineChange = (v: String) => {
        val newRow = myData.modify(_.valine).setTo(v)
        setMyData(newRow)
      }
      def caChange = (v: String) => {
        val newRow = myData.modify(_.ca).setTo(v)
        setMyData(newRow)
      }
      def metChange = (v: String) => {
        val newRow = myData.modify(_.met).setTo(v)
        setMyData(newRow)
      }
      def gcaChange = (v: String) => {
        val newRow = myData.modify(_.gca).setTo(v)
        setMyData(newRow)
      }
      def gcdcaChange = (v: String) => {
        val newRow = myData.modify(_.gcdca).setTo(v)
        setMyData(newRow)
      }
      def tcdcaChange = (v: String) => {
        val newRow = myData.modify(_.tcdca).setTo(v)
        setMyData(newRow)
      }

      def refreshPdfInfo = () => {
        val request = UserIdData(id = Tool.getUserId)
        Api.user.getPdfInfo(request).map { x =>
          setPdfInfo(x)
        }
      }

      def getDanger(scoreStr: String) = {
        if (scoreStr.strIsBlank) {
          ""
        } else {
          val score = BigDecimal(scoreStr)
          score match {
            case x if x <= 0.25 => "肝脏代谢指标综合分析良好，提示比较健康，患有慢性肝病的可能性比较低。肝纤维化、肝硬化的可能性比较低。本结果仅供参考。"
            case x if x > 0.25 && x <= 0.5 =>
              "肝脏代谢指标综合分析出现异常，提示患有慢性肝病的可能性非常大。早期肝纤维化的可能性非常大。本结果仅供参考，肝纤维化、肝硬化程度请结合临床。"
            case x if x > 0.5 && x <= 0.75 =>
              "肝脏代谢指标综合分析出现异常，提示患有慢性肝病的可能性非常大。晚期肝纤维化的可能性非常大。本结果仅供参考，肝纤维化、肝硬化程度请结合临床。"
            case x if x > 0.75 =>
              "肝脏代谢指标综合分析出现异常，提示患有慢性肝病的可能性非常大。肝硬化的可能性非常大。本结果仅供参考，肝纤维化、肝硬化程度请结合临床。"
          }
        }
      }

      def fillMyData = {
        val newMyData = myData
          .patchUsing(props.row.mission)
          .patchUsing(props.row.extra)
          .patchUsing(props.row.result)
          .modify(_.title)
          .using { x =>
            if (x.strIsBlank) pdfInfo.title else x
          }
          .modify(_.danger)
          .using { x =>
            if (x.strIsBlank) getDanger(props.row.mission.score) else x
          }
          .modify(_.svgStr)
          .setTo($("#svg1").html())
          .modify(_.sampleType)
          .using { x =>
            if (x.strIsBlank) "血浆" else x
          }
          .modify(_.unit)
          .using { x =>
            if (x.strIsBlank) pdfInfo.unit else x
          }
          .modify(_.address)
          .using { x =>
            if (x.strIsBlank) pdfInfo.address else x
          }
          .modify(_.reporter)
          .using { x =>
            if (x.strIsBlank) pdfInfo.reporter else x
          }
          .modify(_.checker)
          .using { x =>
            if (x.strIsBlank) pdfInfo.checker else x
          }
          .modify(_.reportDate)
          .using { x =>
            if (x.strIsBlank) props.time else x
          }
        setMyData(newMyData)
      }
    }

    useEffect(
      () => {
        FTool.fillMyData
      },
      List(props.row, props.time)
    )
    useEffect(
      () => {
        FTool.refreshPdfInfo()
      },
      List()
    )
    val sampleTypeMap = List("血清", "尿液", "粪便", "血浆", "全血", "组织").optionMap

//cancel
    Modal(onHide = FTool.handleClose, show = props.show, size = "modal1000")(
      Modal.Header(bsPrefix = "modal-header bg-primary", closeButton = true)(
        Modal.Title(
          i(className := "fa fa-pencil"),
          span(style := Style(fontWeight = "bold"), id := "lblAddTitle", " 导出Pdf报告")
        )
      ),
      form(
        data - "toggle" := "validator",
        className := "form-horizontal",
        onSubmit := FTool.formSubmit,
        Modal.Body(
          div(
            className := "row-fluid",
            InputInlineCp(
              useForm = useForm,
              label = "标题",
              name = "title",
              labelWidth = 2,
              inputWidth = 3,
              value = myData.title,
              onChange = FTool.titleChange
            ),
            TextareaInlineCp(
              label = "诊断建议",
              name = "danger",
              labelWidth = 2,
              inputWidth = 8,
              value = myData.danger,
              onChange = FTool.dangerChange
            ),
            FormGroupInlineCp(
              useForm = useForm,
              names = List("unit", "address")
            )(
              InputInlineNoFormGroupCp(
                useForm = useForm,
                value = myData.unit,
                label = "送检单位",
                name = s"unit",
                onChange = FTool.unitChange,
                inputWidth = 3
              ),
              InputInlineNoFormGroupCp(
                useForm = useForm,
                value = myData.address,
                label = "地址",
                name = s"address",
                onChange = FTool.addressChange,
                inputWidth = 3
              )
            ),
            FormGroupInlineCp(
              useForm = useForm,
              names = List("name", "sex")
            )(
              InputInlineNoFormGroupCp(
                useForm = useForm,
                value = myData.name,
                label = "姓名",
                name = s"name",
                onChange = FTool.nameChange,
                inputWidth = 3
              ),
              InputInlineNoFormGroupCp(
                useForm = useForm,
                value = myData.sex,
                label = "性别",
                name = s"sex",
                onChange = FTool.sexChange,
                inputWidth = 3
              )
            ),
            FormGroupInlineCp(
              useForm = useForm,
              names = List("age", "office")
            )(
              InputInlineNoFormGroupCp(
                useForm = useForm,
                value = myData.age,
                label = "年龄",
                name = s"age",
                onChange = FTool.ageChange,
                inputWidth = 3,
                readOnly = true
              ),
              InputInlineNoFormGroupCp(
                useForm = useForm,
                value = myData.office,
                label = "送检科室",
                name = s"office",
                onChange = FTool.officeChange,
                inputWidth = 3
              )
            ),
            FormGroupInlineCp(
              useForm = useForm,
              names = List("doctor", "number")
            )(
              InputInlineNoFormGroupCp(
                useForm = useForm,
                value = myData.doctor,
                label = "申请医生",
                name = s"doctor",
                onChange = FTool.doctorChange,
                inputWidth = 3
              ),
              InputInlineNoFormGroupCp(
                useForm = useForm,
                value = myData.number,
                label = "门诊/住院号",
                name = s"number",
                onChange = FTool.numberChange,
                inputWidth = 3
              )
            ),
            FormGroupInlineCp(
              useForm = useForm,
              names = List("sampleTime", "submitTime")
            )(
              DateTimePickerInlineNoFormGroupCp(
                useForm = useForm,
                value = myData.sampleTime,
                label = "采样时间",
                name = s"sampleTime",
                onChange = FTool.sampleTimeChange,
                inputWidth = 3
              ),
              DateTimePickerInlineNoFormGroupCp(
                useForm = useForm,
                value = myData.submitTime,
                label = "送检时间",
                name = s"submitTime",
                onChange = FTool.submitTimeChange,
                inputWidth = 3
              )
            ),
            InputInlineCp(
              useForm = useForm,
              label = "样本号",
              name = "sampleId",
              labelWidth = 2,
              inputWidth = 3,
              value = myData.sampleId,
              onChange = FTool.sampleIdChange
            ),
            FormGroupInlineCp(
              useForm = useForm,
              names = List("sampleTime", "submitTime")
            )(
              SelectInlineNoFormGroupCp(
                useForm = useForm,
                value = myData.sampleType,
                label = "样本类型",
                name = s"sampleType",
                onChange = FTool.sampleTypeChange,
                inputWidth = 3,
                optionMap = sampleTypeMap
              ),
              InputInlineNoFormGroupCp(
                useForm = useForm,
                value = myData.sampleStatus,
                label = "样本状态",
                name = s"sampleStatus",
                onChange = FTool.sampleStatusChange,
                inputWidth = 3
              )
            ),
            FormGroupInlineCp(
              useForm = useForm,
              names = List("sampleTime", "submitTime")
            )(
              InputInlineNoFormGroupCp(
                useForm = useForm,
                value = myData.reporter,
                label = "检验人",
                name = s"reporter",
                onChange = FTool.reporterChange,
                inputWidth = 3
              ),
              InputInlineNoFormGroupCp(
                useForm = useForm,
                value = myData.checker,
                label = "审核人",
                name = s"checker",
                onChange = FTool.checkerChange,
                inputWidth = 3
              )
            ),
            FormGroupInlineCp(
              useForm = useForm,
              names = List("sampleTime", "submitTime")
            )(
              DateTimePickerInlineNoFormGroupCp(
                useForm = useForm,
                value = myData.checkDate,
                label = "检验日期",
                name = s"checkDate",
                onChange = FTool.checkDateChange,
                inputWidth = 3
              ),
              DateTimePickerInlineNoFormGroupCp(
                useForm = useForm,
                value = myData.reportDate,
                label = "报告日期",
                name = s"reportDate",
                onChange = FTool.reportDateChange,
                inputWidth = 3
              )
            ),
            TextareaInlineCp(
              label = "检验方法",
              name = "testMethod",
              labelWidth = 2,
              inputWidth = 8,
              value = myData.testMethod,
              onChange = FTool.testMethodChange
            ),
            h4("数据"),
            FormGroupInlineCp(
              useForm = useForm,
              names = List("sampleTime", "submitTime")
            )(
              InputInlineNoFormGroupCp(
                useForm = useForm,
                value = myData.ast,
                label = "天门冬氨酸氨基转移酶 (U/L)",
                name = s"ast",
                onChange = FTool.astChange,
                inputWidth = 3,
                readOnly = true
              ),
              InputInlineNoFormGroupCp(
                useForm = useForm,
                value = myData.alt,
                label = "丙氨酸氨基转移酶 (U/L)",
                name = s"alt",
                onChange = FTool.altChange,
                inputWidth = 3,
                readOnly = true
              )
            ),
            FormGroupInlineCp(
              useForm = useForm,
              names = List("sampleTime", "submitTime")
            )(
              InputInlineNoFormGroupCp(
                useForm = useForm,
                value = myData.plt,
                label = "血小板计数 (10^9/L)",
                name = s"ast",
                onChange = FTool.pltChange,
                inputWidth = 3,
                readOnly = true
              ),
              InputInlineNoFormGroupCp(
                useForm = useForm,
                value = myData.tca,
                label = "牛磺胆酸 (ng/mL)",
                name = s"tca",
                onChange = FTool.tcaChange,
                inputWidth = 3,
                readOnly = true
              )
            ),
            FormGroupInlineCp(
              useForm = useForm,
              names = List("sampleTime", "submitTime")
            )(
              InputInlineNoFormGroupCp(
                useForm = useForm,
                value = myData.tyr,
                label = "L-酪氨酸 (μmol/L)",
                name = s"tyr",
                onChange = FTool.tyrChange,
                inputWidth = 3,
                readOnly = true
              ),
              InputInlineNoFormGroupCp(
                useForm = useForm,
                value = myData.phe,
                label = "苯丙氨酸 (μmol/L)",
                name = s"phe",
                onChange = FTool.pheChange,
                inputWidth = 3,
                readOnly = true
              )
            ),
            FormGroupInlineCp(
              useForm = useForm,
              names = List("sampleTime", "submitTime")
            )(
              InputInlineNoFormGroupCp(
                useForm = useForm,
                value = myData.valine,
                label = "缬氨酸 (μmol/L)",
                name = s"valine",
                onChange = FTool.valineChange,
                inputWidth = 3,
                readOnly = true
              ),
              InputInlineNoFormGroupCp(
                useForm = useForm,
                value = myData.trp,
                label = "色氨酸 (μmol/L)",
                name = s"trp",
                onChange = FTool.trpChange,
                inputWidth = 3,
                readOnly = true
              )
            ),
            FormGroupInlineCp(
              useForm = useForm,
              names = List("sampleTime", "submitTime")
            )(
              InputInlineNoFormGroupCp(
                useForm = useForm,
                value = myData.met,
                label = "甲硫氨酸 (μmol/L)",
                name = s"met",
                onChange = FTool.metChange,
                inputWidth = 3,
                readOnly = true
              ),
              InputInlineNoFormGroupCp(
                useForm = useForm,
                value = myData.ca,
                label = "胆酸 (μmol/L)",
                name = s"ca",
                onChange = FTool.caChange,
                inputWidth = 3,
                readOnly = true
              )
            ),
            FormGroupInlineCp(
              useForm = useForm,
              names = List("sampleTime", "submitTime")
            )(
              InputInlineNoFormGroupCp(
                useForm = useForm,
                value = myData.gcdca,
                label = "甘氨鹅脱氧胆酸 (μmol/L)",
                name = s"gcdca",
                onChange = FTool.gcdcaChange,
                inputWidth = 3,
                readOnly = true
              ),
              InputInlineNoFormGroupCp(
                useForm = useForm,
                value = myData.gca,
                label = "甘氨氧胆酸 (μmol/L)",
                name = s"gca",
                onChange = FTool.gcaChange,
                inputWidth = 3,
                readOnly = true
              )
            ),
            InputInlineCp(
              useForm = useForm,
              label = "牛磺鹅脱氧胆酸 (μmol/L)",
              name = "tcdca",
              labelWidth = 2,
              inputWidth = 3,
              value = myData.tcdca,
              onChange = FTool.tcdcaChange,
              readOnly = true
            )
          )
        ),
        Modal.Footer(bsPrefix = "modal-footer bg-info")(
          button(`type` := "submit", className := "btn blue", "确定"),
          button(
            `type` := "button",
            className := "btn green",
            data - "dismiss" := "modal",
            "取消",
            onClick := FTool.handleClose
          )
        )
      )
    )
  }

}
